package com.hyy.lotterysystem.controller;

import com.hyy.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.hyy.lotterysystem.common.exception.ControllerException;
import com.hyy.lotterysystem.common.pojo.CommonResult;
import com.hyy.lotterysystem.common.utils.JacksonUtil;
import com.hyy.lotterysystem.controller.param.PasswordLoginParam;
import com.hyy.lotterysystem.controller.param.UserRegisterParam;
import com.hyy.lotterysystem.controller.param.VerifyCodeLoginParam;
import com.hyy.lotterysystem.controller.result.BaseUserInfoResult;
import com.hyy.lotterysystem.controller.result.UserLoginResult;
import com.hyy.lotterysystem.controller.result.UserRegisterResult;
import com.hyy.lotterysystem.service.Impl.VerificationCodeServiceImpl;
import com.hyy.lotterysystem.service.UserService;
import com.hyy.lotterysystem.service.dto.UserDTO;
import com.hyy.lotterysystem.service.dto.UserLoginDTO;
import com.hyy.lotterysystem.service.dto.UserRegisterDTO;
import com.hyy.lotterysystem.service.enums.UserIdentityEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeServiceImpl verificationCodeService;

    //日志打印到UserController中
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /*
     * 注册
     * */
    @RequestMapping("/register")//可以是post
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam param) {//@ResponseBody把前端json转成字符串

        //打印日志
        logger.info("方法：userRegister--> 对象：UserRegisterParam ：{}", JacksonUtil.writeValueAsString(param));

        //调用service，进行访问
        UserRegisterDTO registerDTO = userService.register(param);
        return CommonResult.success(convertToUserRegisterResult(registerDTO));
    }

    /**
     * 密码方式登录
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> passwordLogin(@Validated @RequestBody PasswordLoginParam param) {
        logger.info("通过密码登录，参数param：{}", JacksonUtil.writeValueAsString(param));
        UserLoginDTO dto = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(dto));
    }


    /**
     * 发送验证码
     *
     * @param email
     * @return
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(@RequestParam("phoneNumber") String email) {//阿里云用不了，换成邮箱
        logger.info("sendVerificationCode email:{}", email);
        verificationCodeService.sendVerificationCode(email);
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 验证码登录(message是前端要求的)
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> verifyCodeLogin(@RequestBody VerifyCodeLoginParam param) {
        logger.info("通过验证码登录，参数param：{}", JacksonUtil.writeValueAsString(param));

        UserLoginDTO dto = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(dto));
    }


    /*
    查询指定类型人员列表
    * */
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity){
            logger.info("findBaseUserInfo方法，参数identity:{}", identity);
        List<UserDTO> userDTOList=userService.findUserInfos(UserIdentityEnum.forName(identity));
        return CommonResult.success(convertToList(userDTOList));
    }

    private List<BaseUserInfoResult> convertToList(List<UserDTO> userDTOList) {
        if (CollectionUtils.isEmpty(userDTOList)) {
            return Arrays.asList();
        }

        return userDTOList.stream()
                .map(userDTO -> {
                    BaseUserInfoResult result = new BaseUserInfoResult();
                    result.setUserId(userDTO.getUserId());//id
                    result.setUserName(userDTO.getUserName());//name
                    result.setIdentity(userDTO.getIdentity().name());//identity
                    return result;
                }).collect(Collectors.toList());

    }


    private UserLoginResult convertToUserLoginResult(UserLoginDTO dto) {
        if (dto == null) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult loginResult = new UserLoginResult();
        loginResult.setToken(dto.getToken());
        loginResult.setIdentity(dto.getIdentity().name());
        return loginResult;
    }


    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO registerDTO) {
        UserRegisterResult registerResult = new UserRegisterResult();
        if (registerDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        registerResult.setUserId(registerDTO.getUserId());
        return registerResult;
    }
}
